package com.web.lqj;

import com.entity.Knowledge;
import com.entity.PageManager;
import com.entity.Varietiess;
import com.service.lqj.KnowledgeService;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/knowledge")
@MultipartConfig
public class KnowledgeServlet extends HttpServlet {

    //用户的逻辑层
    private KnowledgeService knowledgeService = new KnowledgeService();

    //request对象
    private HttpServletRequest request;
    //response对象
    private HttpServletResponse response;

    //不管是post还是get请求，都会进入到service
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //初始化请求和响应
        synchronized (this) {
            this.request = request;
            this.response = response;
            String method = request.getParameter("method");
            switch (method) {
                case "index": queryKnowledge();break;
                case "toAddPage": toAddPage();break;
                case "add": addKnowledge();break;
                case "del": delKnowledge();break;
                case "showPic": showPic(); break;
                case "queryKnowledge": queryKnowled(); break;
                case "update": update(); break;
                case "indexto": index();break;
                case "details": details();break;
            }
        }
    }

    private void details() throws ServletException, IOException {
        String title = request.getParameter("title");
        Knowledge knowledge = knowledgeService.queryKnowledge(title);
        System.out.println(knowledge);
        request.setAttribute("Knowledge", knowledge);
        request.setAttribute("outerLi", "knowledge");
        request.setAttribute("innerLi", "showKnowledge");
        WebUtils.toRequestPageVarietiess(request, response, "raise");
    }

    private void index() throws ServletException, IOException {
        PageManager pm = WebUtils.getBean(PageManager.class, request);
        List<Knowledge> knowledges = knowledgeService.queryKnowledge(pm);
        int totalCount = knowledgeService.queryknowledgeTotalCount();
        pm.setTotalCount(totalCount);//总数据数
        pm.setPages();//设置总页数
        request.setAttribute("knowledge", knowledges);
        request.getSession().setAttribute("pm", pm);
        request.setAttribute("outerLi", "knowledge");
        request.setAttribute("innerLi", "showKnowledge");
        WebUtils.toRequestPageVarietiess(request, response, "choose");
    }

    private void update() throws IOException, ServletException {
        Knowledge knowledge = WebUtils.getBean(Knowledge.class, request);
        String path1 = WebUtils.uploadFile(request, "newPic1", WebUtils.SAVE_PATH);
        //如果path是空，新的图片没上传，不做修改
        knowledge.setPic(path1==null?knowledge.getPic():path1);
        String path2 = WebUtils.uploadFile(request, "newPic2", WebUtils.SAVE_PATH);
        //如果path是空，新的图片没上传，不做修改
        knowledge.setPicture(path2==null?knowledge.getPicture():path2);
        //修改
        boolean result = knowledgeService.updateKnowledge(knowledge);
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        request.getSession().setAttribute("msg", result?"修改成功":"修改失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("knowledge?method=index&pn="+(pm==null?"":pm.getPn()));
    }

    private void queryKnowled() throws ServletException, IOException {
        String title = request.getParameter("title");
        Knowledge knowledge = knowledgeService.queryKnowledge(title);
        request.setAttribute("Knowledge", knowledge);
        request.setAttribute("outerLi", "knowledge");
        request.setAttribute("innerLi", "showKnowledge");
        WebUtils.toRequestPageKnowledge(request, response, "updateKnowledge");
    }

    private void showPic() throws IOException {
        String pic = request.getParameter("pic");
        File file = new File(pic);

        //将图片的字节写入到页面
        //jsp中的out写入东西
        OutputStream out = response.getOutputStream();
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
        response.flushBuffer();//刷新缓存
    }

    private void delKnowledge() throws IOException {
        String knowledge = request.getParameter("title");
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()-1);
            pm.setPages();
            //删除之后，正好最后一页没了，直接使用最后一页当作当前页
            pm.setPn(pm.getPn()>=pm.getPages()?pm.getPages():pm.getPn());
        }
        boolean result = knowledgeService.delKnowledge(knowledge);
        request.getSession().setAttribute("msg", result?"删除成功":"删除失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("knowledge?method=index&pn="+((pm==null)?"":pm.getPn()));
    }

    private void addKnowledge() throws IOException, ServletException {
        //转化为实体类
        Knowledge knowledge = WebUtils.getBean(Knowledge.class, request);

        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()+1);
            pm.setPages();
        }

        //设置时间
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        knowledge.setTime(simpleDateFormat.format(date));
        //重新设置文件路径
        knowledge.setPic(WebUtils.uploadFile(request, "pic", WebUtils.SAVE_PATH));
        knowledge.setPicture(WebUtils.uploadFile(request, "picture", WebUtils.SAVE_PATH));
        boolean result = knowledgeService.addKnowledge(knowledge);
        request.getSession().setAttribute("msg", result?"增加成功":"增加失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("knowledge?method=index&pn="+(pm==null?"":pm.getPages()));
    }

    private void toAddPage() throws ServletException, IOException {
        request.setAttribute("outerLi", "knowledge");
        request.setAttribute("innerLi", "showKnowledge");
        WebUtils.toRequestPageKnowledge(request, response, "addKnowledge");
    }

    private void queryKnowledge() throws ServletException, IOException {
        PageManager pm = WebUtils.getBean(PageManager.class, request);
        List<Knowledge> knowledges = knowledgeService.queryKnowledge(pm);
        int totalCount = knowledgeService.queryknowledgeTotalCount();
        pm.setTotalCount(totalCount);//总数据数
        pm.setPages();//设置总页数
        for (Knowledge knowledge : knowledges) {
            System.out.println(knowledge);
        }
        request.setAttribute("knowledge", knowledges);
        request.getSession().setAttribute("pm", pm);
        request.setAttribute("outerLi", "knowledge");
        request.setAttribute("innerLi", "showKnowledge");
        WebUtils.toRequestPageKnowledge(request, response, "showKnowledge");
    }

}
